package cn.edu.imau.zy.system.weChat;

import cn.edu.imau.zy.common.redis.util.RedisUtils;
import cn.edu.imau.zy.common.utils.StringUtils;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @program: xsc-cloud
 * @description: 微信服务端API工具类
 * @author: Wuyz
 * @create: 2020-11-20 13:52
 **/
@Service
public class WeChatApi {

    private static final Logger log = LoggerFactory.getLogger(WeChatApi.class);

    @Autowired
    private RedisUtils redis;

    /**
     * appID
     */
    private static final String appId = "wx3d59d99ca334702c";
    /**
     * 小程序秘钥
     */
    private static final String secret = "5d7287f371c5eddceb5d91d01a2381ea";


    /**
     * 微信登陆/换取登陆信息
     *
     * @param jscode
     * @return
     */
    public String jscode2session(String jscode) {
        return HttpUtil.get("https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + secret + "&js_code=" + jscode + "&grant_type=authorization_code");
    }

    public void subscribeMessageSend(Map<String, Object> params) {
        log.info("发送订阅消息:{}", params);
        String res = HttpRequest.post("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + getAccessToken()).body(new JSONObject(params).toJSONString()).execute().body();
        JSONObject jsonObject = JSONObject.parseObject(res);
        if (jsonObject.getInteger("errcode") == 0) {
            log.info("订阅消息发送成功！");
        } else {
            log.info("订阅消息发送失败！错误码：[{}]", jsonObject.toJSONString());
        }
    }

    public String getAccessToken() {
        String accessToken = redis.get("wx_app_access_token_" + appId);
        if (StringUtils.isEmpty(accessToken)) {
            log.info("重新获取accessToken");
            JSONObject jsonObject = JSONObject.parseObject(HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + secret));
            accessToken = jsonObject.getString("access_token");
            log.info("获取到accessToken:{}", accessToken);
            if (StringUtils.isNotEmpty(accessToken)) {
                redis.set("wx_app_access_token_" + appId, accessToken, 6000);
                log.info("accessToken存入Redis");
            }
        }
        return accessToken;
    }

}
